<?php
namespace app\common\logic;

class AdminLogic
{

	private function M()
	{
		return M('admin');
	}

    public function ls()
    {
        //列表
        $page = isset($_POST['page']) ? $_POST['page'] : 1;
        $page = max($page, 1);
        $size = isset($_POST['size']) ? $_POST['size'] : 15;
        $start = $page * $size - $size;

		$where = parseWhere();
        
        $data = $this->M()->where($where)->order('id desc')->limit($start, $size)->select();
        $total = $this->M()->where($where)->count();
        
        return array('data' => $data, 'total' => $total);
    }
    
    public function get($id)
    {
        $id = (int) $id;
        $row = $this->M()->find($id);
		if(!$row['avatar']) $row['avatar'] = '/static/image/avatar_man.gif';
        return $row;
    }
    
    public function delete($id)
    {
        $rs = $this->M()->where('id', $id)->delete();
        if($rs === false) {
            json(0, '删除失败');
        }
    }

	//编辑自己信息
	public function edit($post)
	{
		$id = (int) $post['id'];
		if($id != ADMIN_ID) error('参数错误');
		if($post['change_pwd'] == '1') {
			$old = $this->M()->where('id', $id)->find();
			if($old['pwd'] != md5($post['old_pwd'])) {
				error('旧密码错误');
			}
			$post['pwd'] = md5($post['new_pwd']);
		}
		if($id) {
			unset($post['user']);
			$rs = $this->M()->update($post);
		}else{
			$rs = $this->M()->insert($post);
		}
		if($rs === false) {
			error('保存失败');
		}
	}

	//管理员编辑用户信息
    public function save($post)
    {
        $id = (int) $post['id'];
		if($post['new_pwd']) {
			$post['pwd'] = md5($post['new_pwd']);
			unset($post['new_pwd']);
		}
        if($id) {
            $rs = $this->M()->update($post);
        }else{
            $rs = $this->M()->insert($post);
        }
		if($rs === false) {
			error('保存失败');
		}
    }

	//修改状态
	public function st($id, $st)
	{
		$rs = $this->M()->where('id', $id)->setField('st', $st);
		if($rs !== false) {
			return true;
		}else{
			error('修改状态错误');
		}
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) error('参数错误');
		$rs = $this->M()->where("id = $id")->delete();
		if($rs === false) {
			error('删除失败');
		}else{
			return true;
		}
	}
}